#include "Share.h"

Thread_Mutex::Thread_Mutex( void )
{
#ifdef WIN32
	this->mutex_ = CreateMutex( NULL, FALSE, NULL );
#else
	pthread_mutex_init( &this->mutex_, NULL );
#endif
}

Thread_Mutex::~Thread_Mutex( void )
{
	close( );
}

int Thread_Mutex::acquire( )
{
#ifdef WIN32

	if( WaitForSingleObject( this->mutex_, INFINITE ) != WAIT_OBJECT_0 )
		return -1;

	return 0;
#else
	pthread_mutex_lock( &this->mutex_ );
	return 0;
#endif // WIN32
}

int Thread_Mutex::release( )
{
#ifdef WIN32
	return ReleaseMutex( this->mutex_ );
#else
	return pthread_mutex_unlock( &this->mutex_ );
#endif
}

int Thread_Mutex::close( )
{
#ifdef WIN32
	return CloseHandle( this->mutex_ );
#else
	return pthread_mutex_destroy( &this->mutex_ );
#endif // WIN32
}


Thread_Condition_Mutex::Thread_Condition_Mutex( Thread_Mutex &mutex )
	:mutex_( mutex )
{
#ifdef WIN32
	this->condition_ = CreateEvent( 0, TRUE, FALSE, NULL );
#else
	pthread_cond_init( &this->condition_, NULL );
#endif
}

Thread_Condition_Mutex::~Thread_Condition_Mutex( )
{
	close( );
}

int Thread_Condition_Mutex::wait( )
{

#ifdef WIN32
	int ret;
	ResetEvent( this->condition_ );

	if(( ret =
	            SignalObjectAndWait( this->mutex_.mutex_,
	                                 this->condition_,
	                                 INFINITE,
	                                 FALSE ) ) != WAIT_OBJECT_0 )
		return ret = GetLastError( );

	mutex_.acquire( );
#else
	pthread_cond_wait( &this->condition_, &this->mutex_.mutex_ );
#endif // WIN32
	return 0;
}

int Thread_Condition_Mutex::signal( )
{
#ifdef WIN32
	return SetEvent( this->condition_ );
#else
	return pthread_cond_signal( &this->condition_ );
#endif
}

int Thread_Condition_Mutex::close( )
{
#ifdef WIN32
	return CloseHandle( this->condition_ );
#else
	return pthread_cond_destroy( &this->condition_ );
#endif
}
